package org.grow.later.download;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Comparator;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ControllerDownload {
    /*    @Value("${download.open-dir}")
        private String dir;*/

    @GetMapping("/")
    public ModelAndView mainFtpPage() throws IOException {

        final String a = System.getProperty("user.home");
        //Path b = Paths.get(a).resolve("main")
        Path b = Paths.get(a);
        List<String> names = Files.list(b)
                .filter(c -> Files.isRegularFile(c))
                //.filter(Files::isHidden)
                .map(d -> d.getFileName().toString())
                .filter(d->!d.toLowerCase().contains("user"))
              //  .sorted((e, d) -> (int) e.charAt(0) - (int) d.charAt(0))
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        return new ModelAndView("fileList") {{
            addObject("files", names);
        }};

    }

    private Integer bufferSize = 100;

    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName,
                         HttpServletResponse response) throws IOException {
        Path file = Paths.get(System.getProperty("user.home")).resolve(fileName);
        if (Files.notExists(file)) response.getWriter().print("notfound" + fileName);

        response.reset();
        response.setContentType("application/x-download");
        response.addHeader("Content-Length", "" + Files.size(file));
        response.addHeader("Content-Disposition", "attachment:filename=" + file.getFileName());
        response.setContentType("application/octet-stream");
        System.out.println(fileName);
        byte[] buffer = new byte[bufferSize * 1024];

        try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(file));
             BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        ) {
            int i =-1;
            while ((i = in.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            out.flush();
//            response.wait();
        } catch (RuntimeException e) {
            System.out.println("download error about" + file.getFileName());
        }

    }
}

